package dal

import (
	"fmt"

	. "7qule.com/sd3/CrossServer/src/bll/challenge/model"
	baseDal "7qule.com/sd3/CrossServer/src/dal"
)

// 擂台对战信息访问结构
type globalChallenge struct{}

// 访问结构对象
var GlobalChallengeDal = new(globalChallenge)

// 初始化
func init() {
	// 注册到同步对象中
	baseDal.GetSyncMgr().RegisterSyncObj(GlobalChallengeDal.TableName())
}

// TableName 表名
func (this *globalChallenge) TableName() string {
	return "g_challenge"
}

// GetData 从数据库获取玩家数据
// dataContainer:玩家对象
// 返回值:
// interface{}:获取到的数据
// error:错误信息
func (this *globalChallenge) GetData() ([]*GlobalChallengeModel, error) {
	sql := "SELECT `PlayerId`,`StageId`,`Rank`,`IsRobot` FROM `g_challenge`;"

	db := baseDal.GetGameDB().DB()
	execResult, err := db.Query(sql)
	if err != nil {
		baseDal.WriteLog("GlobalChallengeModel", err)

		return nil, err
	}

	defer execResult.Close()

	// 读取数据
	var result = make([]*GlobalChallengeModel, 0, 16)
	for execResult.Next() {
		var tempNewItem = NewGlobalChallenge()
		err = execResult.Scan(
			&tempNewItem.PlayerId,
			&tempNewItem.StageId,
			&tempNewItem.Rank,
			&tempNewItem.IsRobot)

		if err != nil {
			baseDal.WriteLog("GlobalChallengeModel", err)
			return nil, err
		}

		result = append(result, tempNewItem)
	}

	return result, nil
}

// Insert 插入数据
// dataContainer:玩家对象
// data:操作的数据项
func (this *globalChallenge) Insert(data *GlobalChallengeModel) {
	sql := fmt.Sprintf("INSERT INTO `g_challenge` (`PlayerId`,`StageId`,`Rank` ,`IsRobot`) VALUES ('%v', '%v', '%v' , %v) ;",
		data.PlayerId,
		data.StageId,
		data.Rank,
		data.IsRobot)

	baseDal.GetGameDB().Exec(sql)
}

// Update 更新数据
// dataContainer:玩家对象
// redisData:最新redis数据
// data:操作的数据项
func (this *globalChallenge) Update(data *GlobalChallengeModel) {
	sql := fmt.Sprintf("UPDATE `g_challenge` SET  `StageId`=%v,`Rank`=%v ,`IsRobot` =%v WHERE `PlayerId`='%v' ;",
		data.StageId,
		data.Rank,
		data.IsRobot,
		data.PlayerId)

	baseDal.GetGameDB().Exec(sql)
}

// Delete 删除数据
// dataContainer:玩家对象
// data:操作的数据项
func (this *globalChallenge) Delete(data *GlobalChallengeModel) {
	sql := fmt.Sprintf("DELETE FROM g_challenge where `PlayerId`='%v' ;", data.PlayerId)

	baseDal.GetGameDB().Exec(sql)
}
